package com.imoresoft.agile.action;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.IData;
import com.imoresoft.agile.entity.Result;
import com.imoresoft.agile.property.AppConstants;
import com.imoresoft.agile.property.SessionConstants;
import com.imoresoft.agile.top.TaobaoUtil;
import com.imoresoft.agile.top.TopConstants;
import com.imoresoft.agile.top.TopService;
import com.imoresoft.magic.util.UserSubscUtil;
import com.taobao.api.domain.User;
import com.taobao.api.domain.UserSubscribe;

public class TopAction extends BaseAction {

	private static final long serialVersionUID = 116650334283619352L;

	private TopService topService;

	private SuperDao superDao;

	private String userId = null;

	private String nick = null;

	private String sessionId = null;

	private String shopURL = null;

	public TopAction() throws SQLException {
		superDao = new SuperDaoImpl(pd.getConn());
		topService = new TopService(TopConstants.EVN_SWITCH,
				TopConstants.APP_KEY, TopConstants.APP_SECRET);
	}

	public String execute() {
		// 验证参数签名
		boolean isSignValid = validSign();
		if (!isSignValid) {
			return LOGIN;
		}
		logger.info(nick + "登录验证通过");

		// 验证用户使用权限是否到期
		if (validUserSubsc() == false) {
			return LOGIN;
		}
		logger.info(nick + "订购验证通过");

		// 验证用户是否有店铺，没有店铺禁止登录
		shopURL = topService.getShopURL(nick);
		pd.setSessionAttribute(SessionConstants.SESSION_SHOP, shopURL);
		if ("#".equals(shopURL))
			return LOGIN;

		// 新增或更新用户数据
		addOrUpdateUser();

		// 记录登录日志
		loginLog();

		return SUCCESS;
	}

	private boolean validSign() {
		boolean isSignValid = true;
		String appKey = pd.getRequestParameter("top_appkey");
		String parameters = pd.getRequestParameter("top_parameters");
		String sign = pd.getRequestParameter("top_sign");
		sessionId = pd.getRequestParameter("top_session");

		Map<String, String> params = new HashMap<String, String>();
		params.put("top_appkey", appKey);
		params.put("top_parameters", parameters);
		params.put("top_session", sessionId);

		try {
			isSignValid = TaobaoUtil.validateSign(sign, params,
					TopConstants.APP_SECRET);
		} catch (Exception e) {
			logger.warn("validateSign验证失败,打印请求参数：");
			logger.warn("top_appkey==" + appKey);
			logger.warn("top_parameters==" + parameters);
			logger.warn("top_session==" + sessionId);
			logger.warn("top_sign==" + sign);
			logger.warn("validateSign验证失败,请求参数打印完毕.");
			isSignValid = false;
			return isSignValid;
		}

		Map<String, String> userParam = null;
		if (isSignValid) {
			userParam = TaobaoUtil.convertBase64StringtoMap(parameters);
			userId = userParam.get("visitor_id");
			nick = userParam.get("visitor_nick");
		}
		return isSignValid;
	}

	@SuppressWarnings("unchecked")
	private void addOrUpdateUser() {
		IData userParams = new DataMap();
		userParams.put("USER_ID", userId);
		IData userMap = new DataMap();
		try {
			userMap = superDao.queryByPK("TF_S_USER", userParams);
		} catch (Exception e) {
			logger.warn("获取TF_S_USER出错", e);
		}

		User user = topService.getUser(nick, sessionId);
		if (userMap.size() <= 0) {// 新增
			userParams.put("NICK", nick);
			userParams.put("SESSION_ID", sessionId);
			userParams.put("SHOP_URL", shopURL);
			userParams.put("PROV", user.getLocation().getState());
			userParams.put("CITY", user.getLocation().getCity());
			userParams.put("SHOP_TYPE", user.getType());
			userParams.put("SELLER_CREDIT_LEVEL", user.getSellerCredit()
					.getLevel());
			userParams.put("SELLER_CREDIT_SCORE", user.getSellerCredit()
					.getScore());
			userParams.put("EMAIL", user.getEmail());
			userParams.put("ALIPAY_ACCOUNT", user.getAlipayAccount());
			userParams.put("LAST_VALID_TIME", pd.getTime());
			userParams.put("FIRST_LOGIN_TIME", pd.getTime());
			userParams.put("VALID_FLAG", AppConstants.FLAG_YES);
			try {
				superDao.insert("TF_S_USER", userParams);
			} catch (Exception e) {
				logger.warn("新增TF_S_USER出错", e);
			}
			pd.setSessionAttribute(SessionConstants.SESSION_TOP, userParams);
		} else {// 更新
			userParams.put("SESSION_ID", sessionId);
			userParams.put("LAST_VALID_TIME", pd.getTime());
			userParams.put("SESSION_ID", sessionId);
			userParams.put("SELLER_CREDIT_LEVEL", user.getSellerCredit()
					.getLevel());
			userParams.put("SELLER_CREDIT_SCORE", user.getSellerCredit()
					.getScore());
			userParams.put("VALID_FLAG", AppConstants.FLAG_YES);
			try {
				superDao.update("TF_S_USER", userParams);
			} catch (Exception e) {
				logger.warn("更新TF_S_USER出错", e);
			}
			userMap.putAll(userParams);// 直接用最新的数据值覆盖
			pd.setSessionAttribute(SessionConstants.SESSION_TOP, userMap);
		}
	}

	private boolean validUserSubsc() {
		UserSubscribe userSubs = null;
		try {
			userSubs = topService.getSubscribeInfo(nick, TopConstants.LEASE_ID);
		} catch (Exception e) {
			logger.warn("获取" + nick + "订购信息过程中出现异常", e);
		}

		Result versionInfo = UserSubscUtil.getUserClass(superDao, userId,
				userSubs);
		if (versionInfo.getCode() < 0) {
			return false;
		}
		pd.setSessionAttribute(SessionConstants.SESSION_USER_SUBSCRIBE,
				versionInfo);

		String welcomInfo = UserSubscUtil.builderOrderStr(versionInfo);
		pd.setSessionAttribute(SessionConstants.SESSION_USER_SUBSCRIBE_INFO,
				welcomInfo);
		pd.setSessionAttribute(SessionConstants.SESSION_NICK, nick);
		return true;
	}

	@SuppressWarnings("unchecked")
	private void loginLog() {
		HttpServletRequest request = pd.getRequest();
		IData login = new DataMap();
		login.put("USER_ID", userId);
		login.put("NICK", nick);
		login.put("LOG_TYPE", "0");
		login.put("LOG_TIME", pd.getTime());
		if (AppConstants.IS_REAL_ENV) {
			login.put("IP", request.getHeader("X-Real-IP"));
		} else {
			login.put("IP", request.getRemoteAddr());
		}
		login.put("BROWSER", request.getHeader("User-Agent"));
		login.put("REFERER", request.getHeader("Referer"));
		try {
			superDao.insert("TL_S_USER_LOGIN", login);
		} catch (Exception e) {
			logger.warn("记录登录日志出错", e);
		}
	}

	public String logout() {
		pd.getSession().invalidate();
		return SUCCESS;
	}

}
